using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;

namespace demo
{
    /// <summary>
    /// 系统信息服务类
    /// 用于将客户端系统信息发送到服务器
    /// </summary>
    public class SystemInfoService
    {
        private const string SYSTEM_INFO_URL = "http://10.1.200.169:82/SystemInfo/InsertSystemInfo";
        private const int TIMEOUT_MILLISECONDS = 30000;

        /// <summary>
        /// 发送系统信息到服务器
        /// </summary>
        /// <param name="systemInfoJson">系统信息JSON字符串</param>
        /// <returns>发送结果</returns>
        public static SystemInfoResponse SendSystemInfo(string systemInfoJson)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(systemInfoJson))
                {
                    return new SystemInfoResponse
                    {
                        Success = false,
                        Message = "系统信息数据不能为空",
                        Data = null
                    };
                }

                // 解析JSON以验证格式
                dynamic systemInfo;
                try
                {
                    systemInfo = JsonConvert.DeserializeObject(systemInfoJson);
                }
                catch (Exception ex)
                {
                    return new SystemInfoResponse
                    {
                        Success = false,
                        Message = $"系统信息JSON格式错误: {ex.Message}",
                        Data = null
                    };
                }

                // 转换为接口所需的格式
                var requestData = ConvertToApiFormat(systemInfo);
                string requestJson = JsonConvert.SerializeObject(requestData);
                
                // 发送POST请求
                string responseContent = HttpPostJson(SYSTEM_INFO_URL, requestJson);
                
                if (string.IsNullOrEmpty(responseContent))
                {
                    return new SystemInfoResponse
                    {
                        Success = false,
                        Message = "服务器无响应",
                        Data = null
                    };
                }

                // 反序列化响应数据
                var result = JsonConvert.DeserializeObject<SystemInfoResponse>(responseContent);
                return result ?? new SystemInfoResponse
                {
                    Success = false,
                    Message = "响应数据格式错误",
                    Data = null
                };
            }
            catch (Exception ex)
            {
                return new SystemInfoResponse
                {
                    Success = false,
                    Message = $"发送系统信息异常: {ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 将SystemInfoHelper的JSON格式转换为接口所需的格式
        /// </summary>
        /// <param name="systemInfo">系统信息动态对象</param>
        /// <returns>接口格式的对象</returns>
        private static object ConvertToApiFormat(dynamic systemInfo)
        {
            try
            {
                // 按照接口文档的JSON格式要求构建数据结构
                return new
                {
                    ComputerName = systemInfo.ComputerName?.ToString() ?? "",
                    IPAddress = new
                    {
                        ActiveIP = systemInfo.IPAddress?.ActiveIP?.ToString() ?? "",
                        AllIPAddresses = systemInfo.IPAddress?.AllIPAddresses ?? new string[0]
                    },
                    OperatingSystem = new
                    {
                        Name = systemInfo.OperatingSystem?.Name?.ToString() ?? "",
                        Version = systemInfo.OperatingSystem?.Version?.ToString() ?? "",
                        Platform = systemInfo.OperatingSystem?.Platform?.ToString() ?? "",
                        ServicePack = systemInfo.OperatingSystem?.ServicePack?.ToString() ?? ""
                    },
                    SystemVersion = systemInfo.SystemVersion?.ToString() ?? "",
                    SystemArchitecture = new
                    {
                        OperatingSystem = systemInfo.SystemArchitecture?.OperatingSystem?.ToString() ?? "",
                        CurrentProcess = systemInfo.SystemArchitecture?.CurrentProcess?.ToString() ?? "",
                        ProcessorArchitecture = systemInfo.SystemArchitecture?.ProcessorArchitecture?.ToString() ?? ""
                    },
                    ProcessorInfo = new
                    {
                        Name = systemInfo.ProcessorInfo?.Name?.ToString() ?? "",
                        CoreCount = systemInfo.ProcessorInfo?.CoreCount ?? 0
                    },
                    MemoryInfo = new
                    {
                        TotalMemoryMB = systemInfo.MemoryInfo?.TotalMemoryMB?.ToString() ?? "",
                        TotalMemoryGB = systemInfo.MemoryInfo?.TotalMemoryGB?.ToString() ?? "",
                        AvailableMemoryMB = systemInfo.MemoryInfo?.AvailableMemoryMB?.ToString() ?? "",
                        WorkingSet = systemInfo.MemoryInfo?.WorkingSet?.ToString() ?? ""
                    },
                    CollectionTime = systemInfo.CollectionTime?.ToString() ?? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                };
            }
            catch (Exception ex)
            {
                throw new Exception($"转换系统信息格式时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// HTTP POST JSON请求方法
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="paramData">JSON参数数据</param>
        /// <param name="headerDic">请求头字典</param>
        /// <param name="method">请求方法</param>
        /// <returns>响应JSON字符串</returns>
        private static string HttpPostJson(string url, string paramData, Dictionary<string, string> headerDic = null, string method = "POST")
        {
            try
            {
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
                wbRequest.KeepAlive = false;
                wbRequest.Method = method;
                wbRequest.ContentType = "application/json";
                wbRequest.Timeout = TIMEOUT_MILLISECONDS;
                wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
                
                if (headerDic != null && headerDic.Count > 0)
                {
                    foreach (var item in headerDic)
                    {
                        wbRequest.Headers.Add(item.Key, item.Value);
                    }
                }
                
                using (Stream requestStream = wbRequest.GetRequestStream())
                {
                    using (StreamWriter swrite = new StreamWriter(requestStream))
                    {
                        swrite.Write(paramData);
                    }
                }
                
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sread = new StreamReader(responseStream))
                    {
                        return sread.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"HTTP请求失败: {ex.Message}");
            }
        }
    }

    /// <summary>
    /// 系统信息响应类
    /// </summary>
    public class SystemInfoResponse
    {
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool Success { get; set; }

        /// <summary>
        /// 响应消息
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 响应数据
        /// </summary>
        public object Data { get; set; }
    }
}